<template>
  <el-dialog
    :title="!dataForm.id ? '新增图书' : '修改图书'"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :lock-scroll="false"
    :default-expanded-keys="defaultkey"
    :default-checked-keys="defaultkey"
    :visible.sync="visible"
  >
    <!-- <div class="mod-config"> -->
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      v-loading="isOnClick"
      label-width="80px"
    >
      <el-form-item label="书名" prop="书名">
        <el-input
          v-model="dataForm.书名"
          placeholder="书名"
          :disabled="
            dataForm.id != null &&
              dataForm.id != '' &&
              dataForm.id != '0' &&
              dataForm.userNo != null
          "
        ></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="作者">
        <el-input v-model="dataForm.作者" placeholder="作者"></el-input>
      </el-form-item>

      <el-form-item label="出版者" prop="出版者"> 
        <el-input v-model="dataForm.出版者" placeholder="出版社"></el-input>
      </el-form-item>
      <el-form-item
       label="出版日期"
       prop="出版日期"
      >
        <el-input
          v-model="dataForm.出版日期"
          placeholder="出版日期"
          
        ></el-input>
      </el-form-item>
      <el-form-item
       label="ISBN"
        prop="isbn"
      >
        <el-input
          v-model="dataForm.isbn"
          placeholder="ISBN"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="所属分类" prop="mobile">
        <el-input v-model="dataForm.classcode" placeholder="分类" ></el-input>
      </el-form-item> -->
      <el-form-item label="所属分类" prop="classcode">
    <el-cascader ref="cls" class="cascadert" :show-all-levels="false" 
    v-model="defaultkey1"
    :options="bookcls"
    :props="{ multiple: true, checkStrictly: true,...props }"
    clearable></el-cascader>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :disabled="isOnClick"
        >确定</el-button
      >
    </span>
    <!-- </div> -->
  </el-dialog>
</template>

<script>




import { getbookbyid,getbookcls,saveOrUpdate } from '@/api/book/index'
import { reactive } from 'vue';

export default {
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !validatorPassword(value)) {
        callback(new Error('密码要求长度8~20位,并且不能为纯数字或纯字母!'))
      } else {
        callback()
      }
    }
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !validatorPassword(value)) {
        callback(new Error('确认密码要求长度8~20位,并且不能为纯数字或纯字母!'))
      } else if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      isOnClick: false,
      roleList: [],
       bookcls:[],
       defaultkey:[],
       defaultkey1:[],
       props: {
          label: 'name',
          children: 'child',
          value:'code'
        },
      dataForm: {
        id: 0,
        书名: "",
        作者: "",
        出版者: "",
        出版地: "",
        出版日期: "",
        classcode: "",
        isbn:"",
       
      },
      dataRule: {
        userName: [
          { required: true, message: "图书名不能为空", trigger: "blur" }
        ],
        password: [{ validator: validatePassword, trigger: "blur" }],
        comfirmPassword: [
          { validator: validateComfirmPassword, trigger: "blur" }
        ],
        userNo: [
          { required: true, message: "用户账号不能为空", trigger: "blur" }
        ]
        // mobile: [
        //   { required: true, message: '手机号不能为空', trigger: 'blur' },
        //   { validator: validateMobile, trigger: 'blur' }
        // ],
      }
    };
  },  

    created(){
 
    },
  mounted(){
    
  },
  methods: {
  async  init(id) {
     
      this.dataForm.id = id || 0;
          this.visible = true;
           //this.defaultkey1=[];
            this.getbookcls();
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
            //this.$refs.cls.clearCheckedNodes();
            this.$refs.cls.$refs.panel.clearCheckedNodes();
          });
          if (this.dataForm.id) {
          var  data= await  getbookbyid({id:this.dataForm.id})             
              if (data) {
                  this.$refs.cls.$refs.panel.clearCheckedNodes();
                var data=data.data;
                this.dataForm.书名 = data.书名;
                //this.dataForm.salt = data.data.salt
                this.dataForm.isbn = data.isbn;
                this.dataForm.作者 = data.作者;
                this.dataForm.出版者 = data.出版者;
                this.dataForm.classcode = data.classcode;
               // this.defaultkey= data.classcode.split(",")
              //  this.$refs.tree.setCheckedKeys(this.defaultkey);
                this.dataForm.出版日期 = data.出版日期;
           
                //   this.$nextTick(() => {
                 
              console.log("data.classcode", data.classcode)
               var  defaultkeys= data.classcode.split(",")
               console.log("defaultkeys",defaultkeys)
               this.defaultkey1=[];
               //alert(defaultkeys.length)
            var   data1=await  getbookcls({grade:0});
                if(data1&&data1.data){
                 this.bookcls=data1.data;
                for(var i=0;i<defaultkeys.length;i++)
               {  
                
                var defaultkeyss= this.typeEcho(defaultkeys[i],this.bookcls)
                this.defaultkey1.push(defaultkeyss)
                 console.log("11",this.defaultkey1)
               }
                }
                
              }
          
            ;
          } else {
            // this.deptListTreeSetCurrentNode()
          }
        
    },

    typeEcho(pid, treeData) {
   let arr = [];
   let returnArr = [];
   let th = 0;
   function deepFind(childrenData, thN) {
      for (let i = 0; i < childrenData.length; i++) {
         th = thN;
         if (!childrenData[i]?.code) return;
         arr[thN] = childrenData[i].code;
         if (childrenData[i].code == pid) {
             returnArr = arr.slice(0, thN + 1);
             break;
         } else {
             if (childrenData[i].child) {
                th++;
                deepFind(childrenData[i].child, th);
             }
          }
       }
       return returnArr;
     }
      return deepFind(treeData, th);
},

    async getbookcls() {
      var data = await getbookcls({
        grade:0,
      });
      console.log("分类", data.data);
      this.bookcls = data.data;
    },
      getclasscodebylist(arrlist){
        debugger
      var  temp="";
      for(var i=0;i<arrlist.length;i++){
       
        temp+=arrlist[i].slice(0.-1)+",";
        
      }
       return  temp.substring(0,temp.lastIndexOf(","));
      },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          // 密码加密
          const n_pass = this.dataForm.password
            ? encryptDes(this.dataForm.password)
            : null;

          this.isOnClick = true;
          console.log("444",this.getclasscodebylist(this.defaultkey1))
          saveOrUpdate({
              id: this.dataForm.id || undefined,
              书名: this.dataForm.书名,
              isbn:  this.dataForm.isbn,
              作者: this.dataForm.作者,
              出版者: this.dataForm.出版者,
              出版地: this.dataForm.出版地,
              classcode:this.getclasscodebylist(this.defaultkey1),
              出版日期: this.dataForm.出版日期
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success"
                });
                this.isOnClick = false;
                this.visible = false;
                this.$emit("refreshDataList");
                // this.$router.push({ name: "sys_user" });
              } else {
                this.$message.error(data.msg);
              }
            })
            .finally(() => {
              this.isOnClick = false;
            });
        }
      });
    }
  }
};
</script>
<style scoped>
.cascadert{
  width: 100%;
}
</style>
